`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    19:34:15 07/05/2015 
// Design Name: 
// Module Name:    average 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module average(avclk,vt_adc,vt_ave,aclk);
  input avclk;//algorithm clk,61.73KHZ
  input [13:0] vt_adc;//terminal voltage from adc 0~16383
  output [13:0] vt_ave;//average vt
  output aclk;//7.5354HZ
  
  reg state=0;
  //count for 8191 vt_adc values
  reg [12:0] count=13'b0;
  always @(negedge avclk) begin
    count<=count+1;
  end
  
  //accumulate 8191 vt_adc values
  reg [26:0] sum1=27'b0;
  always @(negedge avclk) begin
    if(count==8191) sum1<=27'b0;
    else sum1<=sum1+vt_adc;
  end
  
  //the sum of 8191 vt_adc values
  reg [26:0] sum=27'b0;
  always @(negedge avclk) begin
    if(count==8191) 
		if(state==0 || sum1<sum) sum<=sum1;
  end
  
  //average vt   
  wire [30:0] vt_ave1;
  assign vt_ave1=sum*16;
  assign vt_ave=vt_ave1[30:17];
  
  //state
  always @(negedge avclk) begin
    if(state==0 && count==8191) state=1; 
  end
  
  //aclk
  reg aclk=1;
  always @(negedge avclk) begin
    if(state==1)
	   if(count==10 || count==100) aclk=~aclk;
  end
  
endmodule
